<?php

namespace App\Exceptions;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Reflector;
use Illuminate\Validation\ValidationException;
use ReflectionException;
use ReflectionFunction;
use RuntimeException;
use Throwable;
use Tymon\JWTAuth\Exceptions\JWTException;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
        $this->renderable(function (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->validator->errors()->first(),
            ]);
        });
        $this->renderable(function (JWTException|AuthenticationException $e) {
            return response()->json([
                'success' => false,
                'message' => '登录信息已过期,请重新登录',
                'data'    => ['need_login' => true],
            ]);
        });
    }

    /**
     * @param $request
     * @param Throwable $e
     * @return mixed
     * @throws ReflectionException
     */
    protected function renderViaCallbacks($request, Throwable $e): mixed
    {
        foreach ($this->renderCallbacks as $renderCallback) {
            $ref = new ReflectionFunction($renderCallback);
            $params = $ref->getParameters();
            foreach ($params as $param) {
                $reflector = Reflector::getParameterClassNames($param);
                if (empty($reflector)) {
                    throw new RuntimeException('The given Closure has no parameters.');
                }
                foreach ($reflector as $class) {
                    if ($e instanceof $class) {
                        $response = $renderCallback($e, $request);
                        if (! is_null($response)) {
                            return $response;
                        }
                    }
                }
            }
        }
        return null;
    }
}
